<?php

namespace addons\good\controllers;
use addons\good\models\CategoryModel;
use addons\good\models\GoodsModel;
use controllers\AdminApi;

class index extends AdminApi {
    /**
     * 初始化
     */
    public function onStepUp(){
        $this->model = new GoodsModel();
    }

    /**
     * 分类接口
     * @param string $title
     * @return array
     */
    public function index($title = '') {
        $map = [];
        if ($title){
            $map['a.title like'] = $title;
        }
        $list = $this->model->alias('a')->join('@category as c' , 'c.id = a.category_id')->field('a.*,c.title as category_id')->where($map)->select();
        foreach ($list as $key => &$val){
        	if ($val['category_id'] == ''){
        		$val['category_id'] = '全部';
			}
            $val['image'] = get_image($val['image']);
        }
        return self::returnJson($list);
    }

	/**
	 * 更新前操作
	 * @param array $data
	 * @return bool
	 */
	protected function onUpdateBefore(&$data = []){
		if (self::$post['id']) {
			$find = $this->model->getFind(self::$post['id']);
			if (!$find) {
				$this->error = '商品不存在';
				return false;
			}
		}
		if (self::$post['thumb']) {
			if (!self::$post['thumb'] = $this->uploadImg(self::$post['thumb'], $find['thumb'] ? $find['thumb'] : '')) {
				$this->error = '图片保存失败';
				return false;
			}
		}
		return true;
	}

    public function onFind(){
        // 获取所有的分类
        $categoryModel = new CategoryModel();
        $list = $categoryModel->field('id,title')->select(true)->toArray('id' , 'title');
        if ($list){
        	array_unshift($list , '全部');
		}
        $find = $this->getFind();
        if ($find){
			$find['thumb'] = get_image($find['thumb']);
		}
        return [
            'category' => $this->getSelectOptions($list , $find ? $find['category_id'] : 0) ,
            'find' => $find ,
        ];
    }

	/**
	 * 设置弹窗标题
	 * @return string
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setPageTitle() {
		return '商品';
	}

	/**
	 * 设置面包屑
	 * @return array
	 * @author Colin <amcolin@126.com>
	 * @date 2021-12-30 下午4:05
	 */
	protected static function setCrumbs() {
		return ['商品管理' , '商品列表'];
	}

    /**
     * 删除后
     * @param bool $status
     * @param array $find
     * @return bool
     */
    protected function onDeleteAfter($status, $find = []){
        if ($find['image']){
            unlink(ltrim($find['image'] , '/'));
        }
        return true;
    }
}
